package foodmaterial.filter;

import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession ;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ValidateCodeFilter extends OncePerRequestFilter {

    private static final String regEx = "(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)";

    private static final Pattern pattern = Pattern.compile(regEx,Pattern.CASE_INSENSITIVE);

    private AuthenticationFailureHandler authenticationFailureHandler;

    public ValidateCodeFilter(AuthenticationFailureHandler authenticationFailureHandler) {
        this.authenticationFailureHandler = authenticationFailureHandler ;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        if ("/api/system/userLogin".equals(httpServletRequest.getRequestURI())
             && httpServletRequest.getMethod().equals("POST")) {
            String header = httpServletRequest.getHeader("User-Agent") ;
            Matcher matcher = pattern.matcher(header);
            if (matcher.find() == false) {//不是手机才处验证码
                String verify = httpServletRequest.getParameter("verify");
                if (StringUtils.isEmpty(verify)) {
                    authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, new ValidateCodeException("请输入验证码"));
                    return;
                }
                HttpSession session = httpServletRequest.getSession() ;
                String savedVerity = (String) session.getAttribute("validateCode");
                if (!verify.equals(savedVerity)) {
                    authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, new ValidateCodeException("验证码输入错误"));
                    return;
                }
            }
        }
        filterChain.doFilter(httpServletRequest,httpServletResponse);   //如果不是登录请求，直接调用后面的过滤器链
    }
/*
    static String phoneReg = "\\b(ip(hone|od)|android|opera m(ob|in)i"
            +"|windows (phone|ce)|blackberry"
            +"|s(ymbian|eries60|amsung)|p(laybook|alm|rofile/midp"
            +"|laystation portable)|nokia|fennec|htc[-_]"
            +"|mobile|up.browser|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";
    static String tableReg = "\\b(ipad|tablet|(Nexus 7)|up.browser"
            +"|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";
 */
}
